<template>
  <div class="dailyCenter">
    <el-table-form ref="form" :model="query">
      <el-form-item label="门店" prop="orgSNNo">
        <el-tree-select
          v-model="query.orgSNNo"
          class="tree-select"
          :popover-width="360"
          :select-params="{
            clearable: true,
            placeholder: '请选择门店',
            loading: $loadingPlugin.getTreeData,
          }"
          :tree-params="{
            'default-expand-all': true,
            'expand-on-click-node': false,
            'highlight-current': true,
            props: {
              value: 'orgSNNo',
              label: 'orgName',
              disabled: 'disabled',
            },
            data: treeData,
          }"
          @node-click="selectTreeChange"
        />
      </el-form-item>
      <el-form-item label="日结日期" prop="happendDt">
        <el-date-picker v-model="query.happendDt" type="date" placeholder="选择日期" />
      </el-form-item>
      <el-form-item label="状态" prop="accStatus">
        <el-select v-model="query.accStatus" clearable>
          <el-option label="资金结算待确认" :value="1" />
          <el-option label="资金结算已确认" :value="2" />
          <el-option label="库存结转待确认" :value="3" />
          <el-option label="库存结转已确认" :value="4" />
        </el-select>
      </el-form-item>

      <template v-slot:btns>
        <el-button type="primary" icon="el-icon-search" @click="search">查询</el-button>
      </template>
    </el-table-form>
    <div style="margin-bottom: 10px;" class="btn-group">
      <div>
        <el-button type="primary" icon="el-icon-plus" @click="add">新增日结</el-button>
      </div>
    </div>
    <lb-table
      ref="lbTable"
      v-loading="$loadingPlugin.fetchData"
      v-el-height-adaptive-table="{ bottomOffset: 10 }"
      border
      highlight-current-row
      element-loading-text="加载中"
      header-row-class-name="table-row-name"
      :column="column"
      :data="tableData.data"
      pagination
      :total="tableData.total"
      custom-column
      @fetch="fetchData"
    />

    <AddDialog ref="AddDialogRef" :tree-data="treeData" @refresh="search" />
    <DetailsDialog ref="DetailsDialogRef" />
  </div>
</template>

<script>
  import getTreeData from '@/utils/jsonTree'
  import moment from 'dayjs'
  import { dailyCenterList, dailyCenterConfirm, dailyCenterDel, dailyCenterRevert } from '@/api'
  import { mapGetters } from 'vuex'
  import AddDialog from './components/AddDialog.vue'
  import DetailsDialog from './components/DetailsDialog.vue'
  export default {
    name: 'dailyCenter',
    components: {
      AddDialog,
      DetailsDialog
    },
    data() {
      return {
        treeData: [],
        query: {
          orgSNNo: '', // 适用机构orgSNNo
          happendDt: new Date(), // 日结日期
          accStatus: ''
        },
        tableData: {
          total: 0,
          data: []
        },
        actionColWidth: 80
      }
    },
    computed: {
      ...mapGetters(['orgList']),
      column: function() {
        return [
          {
            type: 'index'
          },
          { label: '门店名称', prop: 'orgName', width: 180, align: 'center' },
          {
            label: '日结时间',
            prop: 'happendTime',
            width: 180,
            align: 'center',
            render: (h, { row }) => (
            <span>
              {row.happendTime && moment(row.happendTime).format('YYYY-MM-DD HH:mm')}
            </span>
          )
          },
          // {
          //   label: "日结门店id",
          //   prop: "orgId",
          //   width: 150,
          //   align: "center",
          // },
          { label: '操作人', prop: 'modifyUser', width: 100, align: 'center' },
          {
            label: '最后操作时间',
            prop: 'modifyTime',
            width: 130,
            align: 'center',
            render: (h, { row }) => (
            <span>{row.modifyTime && moment(row.modifyTime).format('YYYY-MM-DD')}</span>
          )
          },
          {
            label: '日结状态',
            prop: 'carryCenterStatus',
            align: 'center',
            render: (h, { row }) => <span>{this.billStatusFormat(row)}</span>
          },

          {
            label: '操作',
            className: 'action-col',
            width: this.actionColWidth,
            fixed: 'right',
            render: (h, { row, $index }) => {
              return (
              <div>
                { row.carryOverCode && <el-link size='mini' underline={false} onClick={() => this.detali(row)}>
                  明细
                </el-link>}
                {!(row.accStatus === 2 && row.stockStatus === 2) && (
                  <el-link
                    size='mini'
                    underline={false}
                    onClick={() => this.confirm(row)}
                  >
                    日结确认
                  </el-link>
                )}
                {!(row.accStatus !== 1 && row.stockStatus !== 1) && (
                  <el-link size='mini' underline={false} onClick={() => this.del(row)}>
                    删除
                  </el-link>
                )}
                {!(row.accStatus !== 2 && row.stockStatus !== 2) && (
                  <el-link
                    size='mini'
                    underline={false}
                    onClick={() => this.negation(row)}
                  >
                    反日结
                  </el-link>
                )}
              </div>
              )
            }
          }
        ]
      }
    },
    async created() {
      await this.getTreeData()
    },
    methods: {
      // 获取适用机构数据
      async getTreeData() {
        const data = this.orgList.map((item) => ({
          label: item.orgName,
          ...item
        }))
        this.treeData = getTreeData(data)
      },
      // 选择适用机构
      selectTreeChange(value) {
        this.query.orgSNNo = value.orgSNNo
      },
      // 自适应表格列宽
      flexColumnWidth() {
        this.$nextTick(() => {
          let max = 0
          const actionColDom = document.getElementsByClassName('action-col')
          for (let i = 0; i < actionColDom.length; i++) {
            if (actionColDom[i].tagName === 'TD') {
              let width = 20
              const linkDom = actionColDom[i].childNodes[0].childNodes[0].childNodes
              linkDom.forEach((it) => {
                width += it.offsetWidth + 10
              })
              if (width > max) max = width
            }
          }
          this.actionColWidth = max > 60 ? max - 10 : 50
        })
      },
      _getQuery(obj) {
        const query = {}
        for (const key in obj) {
          if (obj.hasOwnProperty(key)) {
            if (obj[key] !== '') {
              query[key] = obj[key]
            }
          }
        }
        return query
      },
      async fetchData({ currentPage, pageSize }) {
        const query = {
          ...this._getQuery(this.query),
          currentPage,
          pageSize
        }

        query.happendDt = moment(query.happendDt).format('YYYY-MM-DD')

        const { status, data } = await dailyCenterList(query)
        if (status === 200) {
          this.tableData.data = data.rows
          if (currentPage === 1) this.tableData.total = data.total
          this.flexColumnWidth()
        }
      },
      billStatusFormat(val) {
        const msg = []
        if (val.accStatus === 1) {
          msg.push('资金结算待确认')
        } else if (val.accStatus === 2) {
          msg.push('资金结算已确认')
        }
        if (val.stockStatus === 1) {
          msg.push('库存结转待确认')
        } else if (val.stockStatus === 2) {
          msg.push('库存结转已确认')
        }
        return msg.join(' | ')
      },
      // 查询
      search() {
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      detali(row) {
        this.$refs['DetailsDialogRef'].show(row)
      },
      add() {
        this.$refs['AddDialogRef'].show()
      },
      // 日结确认
      confirm(row) {
        if (!row.accStatus || row.accStatus <= 0) {
          this.$message.error('资金尚未日结请先日结')
          return
        }
        if (!row.stockStatus || row.stockStatus <= 0) {
          this.$message.error('库存尚未日结请先日结')
          return
        }
        this.confirmSubmit(row)
      },
      async confirmSubmit(row) {
        const params = {
          happendDt: row.happendDt,
          orgId: row.orgId
        }

        const { status } = await dailyCenterConfirm(params)
        if (status === 200) {
          this.$notify({
            title: '提示',
            message: '日结确认成功',
            type: 'success',
            duration: 2000
          })
          this.search()
        }
      },

      // 删除日结
      del(row) {
        this.$confirm(`确认要删除吗？`, '提示', {
          type: 'warning'
        }).then(() => {
          this.delSubmit(row)
        })
      },
      async delSubmit(row) {
        const params = {
          happendDt: row.happendDt,
          orgId: row.orgId
        }

        const { status } = await dailyCenterDel(params)
        if (status === 200) {
          this.$notify({
            title: '提示',
            message: '删除日结成功',
            type: 'success',
            duration: 2000
          })
          this.search()
        }
      },
      // 反日结
      negation(row) {
        this.$confirm(`确认要执行此操作吗？`, '提示', {
          type: 'warning'
        }).then(() => {
          this.negationSubmit(row)
        })
      },
      async negationSubmit(row) {
        const params = {
          happendDt: row.happendDt,
          orgId: row.orgId
        }

        const { status } = await dailyCenterRevert(params)
        if (status === 200) {
          this.$notify({
            title: '提示',
            message: '操作',
            type: 'success',
            duration: 2000
          })
          this.search()
        }
      }
    }
  }
</script>

<style scoped></style>
